package org.cocos2dx.javascript.Camera;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Base64;
import android.util.Log;
import android.widget.Toast;

import org.cocos2dx.javascript.AppActivity;
import org.cocos2dx.javascript.NativeMgr;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxJavascriptJavaBridge;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class CameraMgr {


    private static String TAG = "CameraMgr";

    static String Uid = "";
    private static Uri contentUri;
    private static File tempFile;  //调用照相机返回图片文件
    private static Uri photoUri;

    public static  AppActivity curActivity;
    private static CameraMgr mInstace = null;
    private static final int MAX_IMAGE_SIZE = 1024; // 最大边长限制


    public static CameraMgr getInstance() {
        if (null == mInstace) mInstace = new CameraMgr();
        mInstace.init();
        return mInstace;
    }

    public void init () {
        curActivity = AppActivity.getInstance();
    }
    /**
     * js调用
     * 打开图库实现
     */
    public  void openGallery() {

        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        curActivity.startActivityForResult(intent, curActivity.PHOTO_GALLERY);
    }

    /**
     * js调用
     * 申请权限
     */
    public  void openCamera(){
        String permission = Manifest.permission.CAMERA; //需要的权限
        if(checkPermission(permission)){
            Log.e(TAG, "相机权限已经开启");
            takePhoto();
        }else {
            Log.e(TAG, "相机权限未开启，动态申请权限");
            startRequestPermision(permission);
        }
    }


    /**
     * 检测权限
     */
    private static boolean checkPermission(String permission){
        // 当手机系统大于 23 时，才有必要去判断权限是否获取
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            //检查该权限是否已经获取
            int hasPermission = ContextCompat.checkSelfPermission(curActivity, permission);
            if(hasPermission != PackageManager.PERMISSION_GRANTED){ //权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                return false;
            }else {
                return  true;
            }
        }else {
            return  true;
        }
    }

    /**
     * 开启权限
     */
    private static void startRequestPermision(String perssion){
        ActivityCompat.requestPermissions(curActivity, new String[]{perssion}, AppActivity.CAMERA_PERMISSION_CODE);
    }

    /**
     * 打开相机的实现
     */
    public static void takePhoto(){
        //用于保存调用相机拍照后所生成的文件
        tempFile = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + ".png");
        Log.e(TAG, "打开相机" + tempFile.getPath());

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //判断版本调用系统相机
        //如果在Android7.0以上,使用FileProvider获取Uri
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
            intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            String authority = Cocos2dxActivity.getContext().getPackageName() + ".fileProvider";
            contentUri = FileProvider.getUriForFile(curActivity, authority, tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);


        }else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
        }
        curActivity.startActivityForResult(intent, AppActivity.PHOTO_CAMERA);
    }


    /**
     * 裁剪图片的方法
     * 用于拍照完成或者选择本地图片之后
     * @param uri
     */
    public void startPhotoZoom(Uri uri){
        Log.e(TAG, "startPhotoZoom" + uri);

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

        Log.e(TAG, "裁剪图片的方法1");

        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);
        intent.putExtra("return-data", true);

        Log.e(TAG, "裁剪图片的方法2");

        curActivity.startActivityForResult(intent, AppActivity.PHOTO_CLIP);

        Log.e(TAG, "裁剪图片的方法5");
    }

    /**
     * 操作回调
     * @param requestCode
     * @param resultCode
     * @param data
     */

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "执行intent获取结果data" + data + " requestCode = " + requestCode + " resultCode = " + resultCode);
        switch (requestCode){
            case AppActivity.PHOTO_GALLERY: //获取图库结果，执行裁剪
                if(resultCode == Activity.RESULT_OK){
                    Uri uri = data.getData();
                    //Img2Js(uri);
                    startPhotoZoom(uri);
                }
                break;
            case AppActivity.PHOTO_CAMERA:  //获取拍照结果，执行裁剪
                Log.e(TAG, "获取拍照结果data" + data);
                if(resultCode == Activity.RESULT_OK){   //用相机返回的照片去调用剪裁也需要对Uri进行处理
                    String sPath = "";
                    //如果是7.0android系统，直接获取url
                    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                        sPath = tempFile.getPath();
                    }else {
                        //picture = Uri.fromFile(tempFile);
                        sPath = tempFile.getPath();
                    }
                   
                try {
                        JSONObject mJsonobjData = new JSONObject();
                        mJsonobjData.put("imagePath", sPath);
                        NativeMgr.OnCallBackToJs("PhotoGallery", mJsonobjData.toString());

                    } catch (Exception e) {
                        Log.e("onResp Exception",e.toString());
                    }

                }

            case AppActivity.PHOTO_CLIP: 
                Log.e(TAG, "获取裁剪结果data" + data);
                Bundle bundle = data.getExtras();
                if(bundle!=null){
                    //在这里获得了剪裁后的Bitmap对象，可以用于上传
                    Bitmap image = bundle.getParcelable("data");
                    String path = saveImage(image);
                    if(path!=null){
                        Log.e(TAG, "开始上传喽");
                        //CosManager.getInstance().startUpload(Uid + FileName, path, null);
                    }else {
                        Log.e(TAG, "不能上传喽");
                    }
                }
                break;
        }
    }

    

    
    public void Img2Js(Uri uri) {
        if (uri == null) {   return; }
       
        String[] filePathColumns = { MediaStore.Images.Media.DATA };
        Cursor cursor = AppActivity.getInstance().getContentResolver().query(uri, filePathColumns, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumns[0]);
        if (columnIndex < 0) { return; }
        String imagePath = cursor.getString(columnIndex);
        Bitmap srcBmp = BitmapFactory.decodeFile(imagePath);
            
        try {
            JSONObject mJsonobjData = new JSONObject();
            mJsonobjData.put("imagePath", imagePath);
            NativeMgr.OnCallBackToJs("PhotoGallery", mJsonobjData.toString());
        } catch (Exception e) {
            Log.e("onResp Exception",e.toString());
        }
    }

    
    /**
     * 保存Bitmap到本地的方法
     * @param name
     * @param bmp
     * @return
     */
    public String saveImage(Bitmap bmp) {
        Log.e(TAG, "saveImage");

        File appDir = new File(Environment.getExternalStorageDirectory().getPath());
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        File file = new File(Environment.getExternalStorageDirectory().getPath(), System.currentTimeMillis() + "a.png");
        Log.e(TAG, file.getPath());
        Toast.makeText(curActivity, "保存到" + file.getPath(), Toast.LENGTH_LONG).show();
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
            return file.getAbsolutePath();
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 申请权限回调
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        Log.e(TAG, "申请权限回调");
        if(requestCode == AppActivity.CAMERA_PERMISSION_CODE){
            if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                takePhoto();
            }else {
                //如果拒绝权限且勾选了再也不提醒
                /*if(ActivityCompat.shouldShowRequestPermissionRationale(curActivity, permissions[0]) == false){
                    showDialog();
                }else {
                    goToSetting();
                }*/
                showDialog();
            }
        }
    }

    /**
     * 显示提示框
     */
    private void showDialog(){
        Log.e(TAG, "显示提示框");

        new AlertDialog.Builder(curActivity)
                .setTitle("权限申请")
                .setMessage("请打开相关权限，否则无法正常运行！")
                .setPositiveButton("前去开启", new DialogInterface.OnClickListener() {
                     @Override
                     public void onClick(DialogInterface dialog, int which) {
                         goToSetting();
                     }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                     @Override
                      public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                     }
                  })
                .create()
                .show();
    }

    /**
     * 调到对应的设置界面
     */
    private void goToSetting(){
        Log.e(TAG, "转到设置界面");

        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", curActivity.getPackageName(),  null);
        intent.setData(uri);
        curActivity.startActivityForResult(intent, AppActivity.CAMERA_PERMISSION_CODE);
    }
}
